package com.gexiaobao.pigeon.ui.fragment.mine.tools

import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentVideoTutorialBinding
import com.gexiaobao.pigeon.ui.adapter.VideoAdapter
import com.gexiaobao.pigeon.viewmodel.MineToolsViwModel
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 15:30
 * @Describe    : 视频教程
 */
class FragmentVideoTutorial : BaseFragment<MineToolsViwModel, FragmentVideoTutorialBinding>() {

    private val mAdapter: VideoAdapter by lazy { VideoAdapter() }
    private lateinit var loadsir: LoadService<Any>

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeBar.toolbar.initClose("视频教程") {
            nav().navigateUp()
        }

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 5f)))
            it.initFooter {
                //触发加载更多时请求数据
                mViewModel.getVideo(false)
            }
        }

        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            //点击重试时触发的操作
            loadsir.showLoading()
            mViewModel.getVideo(true)
        }

        mDatabind.layoutList.swipeRefreshLayout.init {
            loadsir.showLoading()
            mViewModel.getVideo(true)
        }

        mAdapter.run {
            setOnItemClickListener { _, _, position ->
                nav().navigateAction(R.id.action_to_video_player, Bundle().apply {
                    putString("title", mAdapter.data[position].tittle)
                    putString("videoUrl", mAdapter.data[position].url)
                    putString("imageUrl", mAdapter.data[position].imageUrl)
                    putString("desc", mAdapter.data[position].desc)
                })
            }
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        showLoading(getString(R.string.loading))
        mViewModel.getVideo(true)
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.videoList.observe(viewLifecycleOwner) {
            loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
        }
    }
}